package com.cy.controller;


import cn.hutool.http.HtmlUtil;
import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cy.common.Constant;
import com.cy.entity.Event;
import com.cy.entity.Message;
import com.cy.entity.User;
import com.cy.service.MessageService;
import com.cy.service.UserService;
import com.cy.util.CommunityUtil;
import com.cy.util.HostHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cy
 * @since 2021-11-08
 */
@Controller
@RequestMapping("/message")
public class MessageController {

    @Resource
    private MessageService messageService;

    @Resource
    private HostHolder hostHolder;

    @Resource
    private UserService userService;


    @GetMapping(path = "/letter/list")
    public String getLetterList(Model model, Integer current, Integer size){
        User user = hostHolder.getUser();

        //分页信息
        if(current == null ){
            current = 1;
        }
        if(size == null){
            size = 10;
        }
        Page<Message> page = new Page<>();
        page.setSize(size);
        page.setCurrent(current);
        model.addAttribute("path", "/message/letter/list");

        //会话列表
        IPage<Message> conversationList = messageService.selectConversations(user.getId(), page);
        List<Map<String, Object>> conversations = new ArrayList<>();
        conversationList.getRecords().forEach(message -> {
                Map<String, Object> map = new HashMap<>();
                map.put("conversation", message);     //某个会话，并且显示最新的会话消息
                map.put("letterCount", messageService.selectLettersCount(message.getConversationId()));    //私信数量
                map.put("unreadCount", messageService.selectLettersCountUnreadCount(user.getId(), message.getConversationId()));   //未读私信数量

                //私信列表显示的头像,如果当前的用户id为fromId,则用户头像为toId
                //反之如果当前用户id为toId则用户头像为fromId
                Integer targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
                map.put("target", userService.findUserById(targetId));
                conversations.add(map);
            }
        );
        model.addAttribute("conversations", conversations);
        model.addAttribute("page", conversationList);  //conversationList里有分页的总数等

        // 查询未读消息数量
        model.addAttribute("letterUnreadCount", messageService.selectLettersCountUnreadCount(user.getId(), null));
        model.addAttribute("noticeUnreadCount", messageService.selectNoticeUnreadCount(user.getId(), null));

        return "/site/letter";
    }


    @GetMapping(path = "/letter/detail/{conversationId}")
    public String getLetterDetail(@PathVariable("conversationId") String conversationId, Page<Message> page, Model model) {
        // 分页信息
        page.setSize(5);
        model.addAttribute("path","/message/letter/detail/" + conversationId);


        // 私信列表
        IPage<Message> letterList = messageService.selectLetters(conversationId, page);
        List<Map<String, Object>> letters = new ArrayList<>();
        if (letterList != null) {
            for (Message message : letterList.getRecords()) {
                Map<String, Object> map = new HashMap<>();
                map.put("letter", message);
                map.put("fromUser", userService.findUserById(message.getFromId()));
                letters.add(map);
            }
        }
        model.addAttribute("letters", letters);

        // 私信目标
        model.addAttribute("target", getLetterTarget(conversationId));
        // 设置已读
        List<Integer> ids = getLetterIds(letterList.getRecords());
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }

        return "/site/letter-detail";
    }


    private User getLetterTarget(String conversationId) {
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);

        if (hostHolder.getUser().getId() == id0) {
            return userService.findUserById(id1);
        } else {
            return userService.findUserById(id0);
        }
    }

    //获取集合中未读私信的集合
    private List<Integer> getLetterIds(List<Message> letterList) {
        List<Integer> ids = new ArrayList<>();
        if (letterList != null) {
            for (Message message : letterList) {
                if (hostHolder.getUser().getId().equals(message.getToId()) && message.getStatus() == 0) {
                    ids.add(message.getId());
                }
            }
        }
        return ids;
    }


    @RequestMapping(path = "/letter/send", method = RequestMethod.POST)
    @ResponseBody
    public String sendLetter(String toName, String content) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", toName);
        User target = userService.getOne(wrapper);
        if (target == null) {
            return CommunityUtil.getJsonString(1, "目标用户不存在!");
        }

        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(target.getId());
        if (message.getFromId() < message.getToId()) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        } else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        message.setContent(content);
        message.setCreateTime(new Date());
        messageService.addMessage(message);

        return CommunityUtil.getJsonString(0);
    }


    @GetMapping(path = "/notice/list")
    public String getNoticeList(Model model){
        User user = hostHolder.getUser();

        // 查询评论通知
        Message message = messageService.selectLatestNotice(user.getId(), Constant.TOPIC_COMMENT);

        if(message != null){
            Map<String, Object> messageVo = new HashMap<>();
            messageVo.put("message", message);

            //将内容中的转义字符还原
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVo.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVo.put("entityType", data.get("entityType"));
            messageVo.put("entityId", data.get("entityId"));
            messageVo.put("postId", data.get("postId"));

            int count = messageService.selectNoticeCount(user.getId(), Constant.TOPIC_COMMENT);
            messageVo.put("count", count);

            int unread = messageService.selectNoticeUnreadCount(user.getId(), Constant.TOPIC_COMMENT);
            messageVo.put("unread", unread);
            model.addAttribute("commentNotice", messageVo);

        }


        // 查询点赞类通知
        message = messageService.selectLatestNotice(user.getId(), Constant.TOPIC_LIKE);

        if(message != null){
            Map<String, Object> messageVo = new HashMap<>();
            messageVo.put("message", message);

            //将内容中的转义字符还原
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVo.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVo.put("entityType", data.get("entityType"));
            messageVo.put("entityId", data.get("entityId"));
            messageVo.put("postId", data.get("postId"));

            int count = messageService.selectNoticeCount(user.getId(), Constant.TOPIC_LIKE);
            messageVo.put("count", count);

            int unread = messageService.selectNoticeUnreadCount(user.getId(), Constant.TOPIC_LIKE);
            messageVo.put("unread", unread);
            model.addAttribute("likeNotice", messageVo);
        }



        // 查询关注类通知
        message = messageService.selectLatestNotice(user.getId(), Constant.TOPIC_FOLLOW);
        if(message != null){
            Map<String, Object> messageVo = new HashMap<>();
            messageVo.put("message", message);

            //将内容中的转义字符还原
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVo.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVo.put("entityType", data.get("entityType"));
            messageVo.put("entityId", data.get("entityId"));

            int count = messageService.selectNoticeCount(user.getId(), Constant.TOPIC_FOLLOW);
            messageVo.put("count", count);

            int unread = messageService.selectNoticeUnreadCount(user.getId(), Constant.TOPIC_FOLLOW);
            messageVo.put("unread", unread);
            model.addAttribute("followNotice", messageVo);
        }

        // 查询未读消息数量  私信和通知
        model.addAttribute("letterUnreadCount", messageService.selectLettersCountUnreadCount(user.getId(), null));
        model.addAttribute("noticeUnreadCount", messageService.selectNoticeUnreadCount(user.getId(), null));

        return "/site/notice";
    }


    @GetMapping(path = "/notice/detail/{topic}")
    public String getNoticeDetail(@PathVariable("topic") String topic, Page<Message> page, Model model){
        User user = hostHolder.getUser();

        page.setSize(5);
        model.addAttribute("path","/message/notice/detail/" + topic);

        QueryWrapper<Message> wrapper = new QueryWrapper<>();
        wrapper.eq("from_id", 1)
                .eq("to_id", user.getId())
                .eq("conversation_id", topic)
                .ne("status", 2);
        Page<Message> noticeList = messageService.page(page, wrapper);

        List<Map<String, Object>> noticeVoList = new ArrayList<>();

        if(noticeList != null){
            noticeList.getRecords().forEach(notice -> {
                Map<String, Object> map = new HashMap<>();

                // 通知
                map.put("notice", notice);

                // 内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
                map.put("user", userService.findUserById((Integer) data.get("userId")));
                map.put("entityType", data.get("entityType"));
                map.put("entityId", data.get("entityId"));
                map.put("postId", data.get("postId"));

                // 发起点赞、评论、关注的人
                map.put("fromUser", userService.findUserById(notice.getFromId()));

                noticeVoList.add(map);
            });
        }
        model.addAttribute("notices", noticeVoList);

        //设置已读
        List<Integer> ids = getLetterIds(noticeList.getRecords());      // 获取未读消息的所有id
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }

        return "/site/notice-detail";
    }



}
